from random import *
from AIFromString import *

class RandomSimpleAIGenerator():
    
    def __init__(self):
        self.tokens = [ 'if ', 'while ', 
                        'not ', 'and ', 'or ',
                        '== ', '> ', '< ', '>= ', '<= '
                        '= ', '+ ', '- ', '* ', '/ ',
                        '\n', '\t', ':\n\t' ]
        self.literals = [ 'LIT ', 'LIT ', 'LIT ', 'LIT ' ]
        self.expressions = [ 'EXPR ', 'EXPR ', 'EXPR ', 'EXPR ' ]
        self.elements = self.tokens + self.literals + self.expressions
        
        self.counter = 0
    
    def validSyntax(self, minLength, maxLength):
        
        
        valid_syntax = False
        
        while not valid_syntax:
            
            # count 'em
            self.counter += 1
            if ( self.counter % 10000 == 0 ):
                print "random ai #%d:\r" % self.counter
            
            # Generate random AI
            
            ai_string = ""
            for i in range(1,randint(minLength,maxLength)):
                ai_string += choice(self.elements)
                i+=1
            
            #print "============================"
            #print ai_string
            
            try:
                ai = compile(ai_string,'<string>','exec')
            except SyntaxError:
                valid_syntax = False
            else:
                valid_syntax = True
                print "Valid Syntax!"
                #DEBUG BELOW
                ai = ai_string
        
        return ai

    
if __name__ == "__main__":
    
    r_simp = RandomSimpleAIGenerator()
    
    f = file('random_valid_syntax','a')
    
    count = 0
    
    while True:
        count += 1
        f.write(r_simp.validSyntax(20,25) + "\n@\n")
        if (count > 5):
            f.flush()
            count = 0
        